package com.mrjoew.weekend.services.impl.sys;

import com.google.common.collect.Lists;
import com.mrjoew.weekend.constants.SecurityConstant;
import com.mrjoew.weekend.entities.WeekendUserDetails;
import com.mrjoew.weekend.entities.po.SysAccountPO;
import com.mrjoew.weekend.repositories.sys.SysAccountRepository;
import com.mrjoew.weekend.services.sys.SysAccountService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.List;
import java.util.Optional;

/**
 * @author Christopher Jones
 * @ClassName UserServiceImpl
 * @explain
 * @date 2020/6/17 0017 14:55
 */
@Slf4j
@Transactional
@Service
public class SysAccountServiceImpl implements SysAccountService, UserDetailsService {

    private final SysAccountRepository sysAccountRepository;

    @Autowired
    public SysAccountServiceImpl(SysAccountRepository sysAccountRepository) {
        this.sysAccountRepository = sysAccountRepository;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Optional<SysAccountPO> existSysAccount = sysAccountRepository.findFirstByAccount(username);

        if (!existSysAccount.isPresent()) {
            throw new UsernameNotFoundException(SecurityConstant.USER_NAME_NOT_FOUND);
        }
        List<GrantedAuthority> authorities = Lists.newArrayList();
        authorities.add(new SimpleGrantedAuthority("ADMIN"));

        WeekendUserDetails userDetails = new WeekendUserDetails(
                existSysAccount.get().getAccount(),
                existSysAccount.get().getPassword(),
                true, true, true, true,
                authorities);
        userDetails.setId(existSysAccount.get().getId());
        return userDetails;
    }

    @Override
    public SysAccountPO save(SysAccountPO sysAccountPO) {
        return sysAccountRepository.save(sysAccountPO);
    }

    @Override
    public List<SysAccountPO> list(SysAccountPO sysAccountPO) {
        return sysAccountRepository.findAll();
    }
}
